<template>
  <el-dialog :title="title" :visible.sync="dialogShow" width="30%" @close="closeDialog">
    <!--绘制表单-->
    <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="formData.name"/>
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="formData.code"/>
      </el-form-item>
      <el-form-item label="权限描述" prop="description">
        <el-input v-model="formData.description"/>
      </el-form-item>
      <el-form-item label="是否可用" prop="enVisible">
        <el-switch
          v-model="formData.enVisible"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitPerm">提交</el-button>
        <el-button @click="dialogShow = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { addPermissionApi, editPermissionApi, getPermissionInfoApi } from '@/api/permission'

export default {
  name: 'AddPerm',
  data() {
    return {
      // 3个变量
      dialogShow: false,
      formData: {
        name: '',
        code: '',
        description: '',
        type: '', // 权限类型 1：菜单 2：按钮
        pid: '', // 父级id
        enVisible: '0'
      },
      formRules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入权限标识', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入权限描述', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '修改权限' : '新增权限'
    }
  },
  methods: {
    // 提交权限
    async submitPerm() {
      try {
        await this.$refs.form.validate()
      } catch (error) {
        return console.log(error)
      }
      if (this.formData.id) {
        await editPermissionApi(this.formData)
        this.$message.success('修改权限成功')
      } else {
        await addPermissionApi(this.formData)
        this.$message.success('添加权限成功')
      }
      this.$emit('update')
      this.dialogShow = false
    },
    // 关闭弹窗事件
    closeDialog() {
      this.formData = {
        name: '',
        code: '',
        description: '',
        type: '', // 权限类型 1：菜单 2：按钮
        pid: '', // 父级id
        enVisible: '0'
      }
      this.$refs.form.clearValidate()
    },
    // 回显数据
    async getRowInfo(id) {
      const res = await getPermissionInfoApi(id)
      console.log(res)
      this.formData = res
      this.dialogShow = true
    }
  }
}
</script>

<style scoped>

</style>
